<?php

namespace Common\Libiary;

    class ClientApiHttp {

        public $timeout = 10;
        public $connecttimeout = 10;
        public $ssl_verifypeer = FALSE;
        public $useragent = 'apex sdk';
        public $version = CLIENT_API_VERSION;
        public  $preix = CLIENT_API_CN;

        function https_request ($api, $data = null, $header = array()) {

            $header = Array('Content-type: application/x-www-form-urlencoded');
            $data = array_merge($data,$this->build_params());
            $url = $this->preix .$api;
            if($_GET['debug']==1){
                var_dump($data);
                exit();
            }
            $curl = curl_init();
            if ( count( $header ) > 0 ) {
                curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
            }
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_TIMEOUT,5);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
            }
            $output = curl_exec($curl);
            $status   = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            $info = curl_getinfo( $curl );
            curl_close($curl);
            list($header, $body) = explode("\r\n\r\n", $output, 2);
            return json_decode($output,true);
        }


        function getHeader($ch, $header) {
            $i = strpos($header, ':');
            if (!empty($i)) {
                $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
                $value = trim(substr($header, $i + 2));
            }
            return strlen($header);
        }


        //生成签名算法
        public function build_params() {
            $time = time();
            $params['nonce'] = $this->createNoncestr();
            $params['time'] = $time;
            $sk = C('APP_PRIVATE_KEY');
            $sk = 'x2LCe2tq@dM5=T5!8pmoAwf5k0v';
            $querystring_arrays = Array($sk, $time, $params['nonce']);
            sort($querystring_arrays,SORT_STRING);//进行排序
            $tmpStr      = implode( $querystring_arrays);
            $sn          = sha1( $tmpStr );
            $params['sign'] = strtoupper($sn);
            $params['jkversion']  = $this->version;
            return $params;
        }


        //生成随机串
        private function createNoncestr( $length = 16 )  {
            $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
            $str ="";
            for ( $i = 0; $i < $length; $i++ )  {
                $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
            }
            return $str;
        }

    }
